package com.rupeng.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.pojo.Card;
import com.rupeng.pojo.Chapter;
import com.rupeng.pojo.Segment;
import com.rupeng.pojo.User;
import com.rupeng.pojo.UserCard;
import com.rupeng.service.CardService;
import com.rupeng.service.ChapterService;
import com.rupeng.service.UserCardService;
import com.rupeng.service.UserSegmentService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;

@Controller
@RequestMapping("/card")
public class CardController {
	@Autowired
	private CardService cardService;
	@Autowired
	private UserCardService userCardService;
	@Autowired
	private UserSegmentService userSegmentService;
	@RequestMapping("/detail.do")
	public ModelAndView detail(Long id, HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		UserCard userCard = new UserCard();
		userCard.setUserId(user.getId());
		userCard.setCardId(id);
		userCard = userCardService.selectOne(userCard);
		if (userCard==null) {
			return new ModelAndView("message", "message", "用户不拥有此学习卡");
		} else if (userCard.getEndTime().getTime()<System.currentTimeMillis()) {
			return new ModelAndView("message", "message", "这张学习卡已经过期");
		}
		ModelAndView modelAndView = new ModelAndView();
		long remainValidDays = CommonUtils.calculateApartDays(new Date(), userCard.getEndTime());
		modelAndView.addObject("remainValidDays", remainValidDays);
		//查询出当前用户最后一次观看的segment的id
        Long latestSegmentId = userSegmentService.selectLatestSegmentId(user.getId());
        modelAndView.addObject("latestSegmentId", latestSegmentId);
        //查询出此学习卡信息
		Card card = cardService.selectOne(id);
		modelAndView.addObject("card", card);
		//查询出此学习卡所有的课程信息
        Map<Chapter, List<Segment>> courseMap = cardService.selectAllCourse(id);
        modelAndView.addObject("courseMap", courseMap);
		return modelAndView;
	}
	@RequestMapping(value="/list.do", method=RequestMethod.POST)
	public @ResponseBody AjaxResult list(HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute("user");
		List<Card> cards = userCardService.selectSecondListByFirstId(user.getId());
        return AjaxResult.successInstance(cards);
    }
}
